package com.hhp.hhptt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhp.hhptt.common.Constants;
import com.hhp.hhptt.common.Result;
import com.hhp.hhptt.controller.dto.UserDTO;
import com.hhp.hhptt.entity.People;
import com.hhp.hhptt.entity.User;
import com.hhp.hhptt.exception.ServiceException;
import com.hhp.hhptt.mapper.PeopleMapper;
import com.hhp.hhptt.mapper.UserMapper;
import com.hhp.hhptt.service.IPeopleService;
import com.hhp.hhptt.service.UserService;
import com.hhp.hhptt.utils.TokenUtils;
import com.mysql.cj.util.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    public boolean saveUser(User user){
//        if(user.getId()!=null){
//         return save(user);
//        }else{
//            return  updateById(user);
//        }
        return saveOrUpdate(user);

    }

    @Override
    public User register(UserDTO userDTO) {
        User user = getUserInfo(userDTO);
        if(user == null){
           user = new User();
           BeanUtil.copyProperties(userDTO,user,true);
           save(user);
        }else{
            throw new ServiceException(Constants.CODE_600,"用户已经存在！");

        }
        return user;
    }
    public UserDTO login(UserDTO userDTO) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username",userDTO.getUsername());
            queryWrapper.eq("password",userDTO.getPassword());
            User one = null;
            try {
                one = getOne(queryWrapper);
            } catch (Exception e) {
                log.error(""+e);
                throw new ServiceException(Constants.CODE_500,"系统错误");
            }if(one!=null){
                    BeanUtil.copyProperties(one,userDTO,true);
                    String token = TokenUtils.getToken(one.getId().toString(),one.getId().toString());
                    userDTO.setToken(token);
                    return userDTO;
                }else{
                    throw new ServiceException(Constants.CODE_600,"用户名密码错误");
                }



        }

   public User getUserInfo(UserDTO userDTO){
       QueryWrapper<User> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("username",userDTO.getUsername());
       queryWrapper.eq("password",userDTO.getPassword());
       User one = null;
       try {
           one = getOne(queryWrapper);
       } catch (Exception e) {
           log.error(""+e);
           throw new ServiceException(Constants.CODE_500,"系统错误");
       }
       return one;
   }

}

